﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using OpenQuarters.WebQuarters.Core;
using OpenQuarters.WebQuarters.Utils;
using OpenQuarters.WebQuarters.Modules.ItemList;

namespace OpenQuarters.WebQuarters.Modules.Feedback
{
    public class FeedbackModule : ItemListModuleBase<Feedback>
    {
        private string introduction_Message = "Please use the form to submit your comments.";

        [Newtonsoft.Json.JsonProperty]
        [PropertyConfiguration(PropertyType.TextBox)]
        public string Introduction_Message
        {
            get { return introduction_Message; }
            set { introduction_Message = value; }
        }

        private string success_Message = "Thank you leaving us your comments.";

        [Newtonsoft.Json.JsonProperty]
        [PropertyConfiguration(PropertyType.TextBox)]
        public string Success_Message
        {
            get { return success_Message; }
            set { success_Message = value; }
        }

        public static Dictionary<string, string> AvailableForms
        {
            get
            {
                Dictionary<string, string> d = new Dictionary<string, string>();
                d.Add("OpenQuarters.WebQuarters.Modules.Feedback,Forms.Default.tpl", "[Default]");

                foreach (string path in System.IO.Directory.GetFiles(Oracle.Request.MapPath("~/Forms/"), "*.tpl"))
                {
                    d.Add(System.IO.Path.GetFileNameWithoutExtension(path), System.IO.Path.GetFileName(path));
                }

                return d;
            }
        }

        private string form = "OpenQuarters.WebQuarters.Modules.Feedback,Forms.Default.tpl";

        [Newtonsoft.Json.JsonProperty]
        [PropertyConfiguration(PropertyType.DropDown, OptionSource = "OpenQuarters.WebQuarters.Modules.Feedback.FeedbackModule.AvailableForms")]
        public string Form
        {
            get { return form; }
            set { form = value; }
        }

        private bool use_JavaScript = false;

        [Newtonsoft.Json.JsonProperty]
        [PropertyConfiguration(PropertyType.CheckBox)]
        public bool Use_JavaScript
        {
            get { return use_JavaScript; }
            set { use_JavaScript = value; }
        }

        public FeedbackModule()
            : base()
        {
        }

        public override void Initialise()
        {
            this.ModuleName = "Feedback Module";
            this.ModuleDescription = "Provides a list of customer feedback together with a submission form";
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            var resp = JFormResponse<DefaultJFormClass>.Current;

            if (resp != null && resp.success)
            {
                this.Controls.AddAt(0, new LiteralControl("<span class=\"message\">" + this.success_Message + "</span>"));
                JFormResponse<DefaultJFormClass>.Current = null;
            }
            else
            {
                if (form.IndexOf(",") == -1 && System.IO.File.Exists(Server.MapPath("~/Forms/" + form + ".tpl")))
                {
                    this.Controls.AddAt(0, new JForm(form, "/cms/modules/MethodHandler/OpenQuarters.WebQuarters.Modules.Feedback,FeedbackModule,FormHandler", new { })
                    {
                        UseJavaScript = this.use_JavaScript,
                    });
                }
                else
                {
                    this.Controls.AddAt(0, new JForm(form, JForm.TemplateType.EmbeddedResource, "/cms/modules/MethodHandler/OpenQuarters.WebQuarters.Modules.Feedback,FeedbackModule,FormHandler", new { })
                    {
                        UseJavaScript = this.use_JavaScript,
                    });
                }

                if (!string.IsNullOrEmpty(this.introduction_Message))
                    this.Controls.AddAt(0, new LiteralControl("<span class=\"message\">" + this.introduction_Message + "</span>"));
            }
        }

        [Invokable]
        public static string FormHandler(HttpRequest request)
        {
            var resp = new JFormResponse<DefaultJFormClass>();

            Feedback feedback = new Feedback();
            feedback.CMSPageId = CMSPage.Current.CMSPage.PageId;
            feedback.DateCreated = DateTime.Now;
            feedback.Moderated = Feedback.ModerationStatus.Unmoderated;

            if (Core.User.Current != null)
                feedback.UserId = Core.User.Current.UserId;

            if (!string.IsNullOrEmpty(request.Form["Name"]))
                feedback.Name = request.Form["Name"].StripHTML();
            else
                feedback.Name = "Anonymous";

            if (!string.IsNullOrEmpty(request.Form["Website"]))
                feedback.Website = request.Form["Website"].StripHTML();

            try
            {
                if (!string.IsNullOrEmpty(request.Form["Score"]))
                    feedback.Score = Convert.ToDecimal(request.Form["Score"]);
            }
            catch { }

            if (!string.IsNullOrEmpty(request.Form["Comments"]))
                feedback.Comments = request.Form["Comments"].StripHTML();
            else
                resp.errorMessages.Add("Comment", new List<string> { "You must enter a comment" });

            if (!string.IsNullOrEmpty(request.Form["AdditionalField1"]))
                feedback.AdditionalField1 = request.Form["AdditionalField1"].StripHTML();

            if (!string.IsNullOrEmpty(request.Form["AdditionalField2"]))
                feedback.AdditionalField2 = request.Form["AdditionalField2"].StripHTML();

            if (!string.IsNullOrEmpty(request.Form["AdditionalField3"]))
                feedback.AdditionalField3 = request.Form["AdditionalField3"].StripHTML();

            if (!string.IsNullOrEmpty(request.Form["AdditionalField4"]))
                feedback.AdditionalField4 = request.Form["AdditionalField4"].StripHTML();

            if (!string.IsNullOrEmpty(request.Form["AdditionalField5"]))
                feedback.AdditionalField5 = request.Form["AdditionalField5"].StripHTML();

            if (resp.success)
                feedback.Save();

            JFormResponse<DefaultJFormClass>.Current = resp;

            return resp.ToJSON();
        }
    }
}
